/**
 * 
 */
package com.jfinal.ext.interceptor;

import java.lang.reflect.Field;

import com.jfinal.aop.Enhancer;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.server.Service;

/**
 * @author y.z
 * exception By Controller
 */
public class InjectInterceptor implements Interceptor{
	private static final Log log = Log.getLog(InjectInterceptor.class);
	/* (non-Javadoc)
	 * @see com.jfinal.aop.Interceptor#intercept(com.jfinal.aop.Invocation)
	 */
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		Field[] fields = controller.getClass().getDeclaredFields();
		
        for (Field field:fields){
        	
            if(field.getAnnotation(Service.class)!=null){
            	
            	try {
            		field.setAccessible(true);
					field.set(controller,Enhancer.enhance(field.getType().newInstance()));
					
				} catch (Exception e) {
					log.error("注入失败:"+field.getType());
					e.printStackTrace();
				}
            }
                
        }
        
        inv.invoke();
		
	}
	
}
